package com.hancher.gamelife2.account;

import android.os.Bundle;

import androidx.navigation.Navigation;
import androidx.sqlite.db.SimpleSQLiteQuery;

import com.hancher.common.androidutil.AsyncUtils;
import com.hancher.common.androidutil.ClipboardUtil;
import com.hancher.common.androidutil.KeyEventUtil;
import com.hancher.common.androidutil.ToastUtil;
import com.hancher.common.base.BaseFragment;
import com.hancher.common.javautil.DecryptUtil;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.common.rv.PageRecyclerViewManager;
import com.hancher.gamelife2.R;
import com.hancher.gamelife2.databinding.FragmentAccountListBinding;
import com.hancher.gamelife2.main.MainDatabase_Impl;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;

import java.util.List;

import io.reactivex.rxjava3.functions.Consumer;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2023/3/12 0012 22:49 <br/>
 * 描述 :
 */
public class AccountListFragment extends BaseFragment<FragmentAccountListBinding> {


    private PageRecyclerViewManager<AccountPO> prvm;

    @Override
    protected void initView(Bundle savedInstanceState) {
        prvm = new PageRecyclerViewManager<AccountPO>()
                .setContext(getContext())
                .setRecyclerView(binding.recyclerview)
                .setAdapter(new AccountAdapter())
                .setDivider(true)
                .setOnItemLongClickListener((baseQuickAdapter, view, i) -> {
                    String item = prvm.getRvList().get(i).getPsd();
                    item = DecryptUtil.decrypt2(item);
                    ToastUtil.show("密码已复制:" + item);
                    ClipboardUtil.copy(item);
//                    jump2Edit(prvm.getRvList().get(i));
                    return true;
                })
                .setOnItemClickListener((baseQuickAdapter, view, i) -> {
                    new XPopup.Builder(getContext())
                            //.maxWidth(600)
                            .atView(view)
                            .popupPosition(PopupPosition.Bottom)
                            .hasShadowBg(false)
                            .animationDuration(0)
                            .asAttachList(new String[]{"编辑", "复制账户", "复制用户名", "复制密码", "删除"},
                                    new int[]{R.drawable.icon_note, R.drawable.icon_account, R.drawable.icon_me, R.drawable.icon_encrypt, R.drawable.icon_delete},
                                    (position, text) -> {
//                                        ToastUtil.show("click " + text);
                                        if ("编辑".equals(text)) {
                                            jump2Edit(prvm.getRvList().get(i));
                                        } else if ("复制用户名".equals(text)) {
                                            ToastUtil.show("用户名已复制:" + prvm.getRvList().get(i).getUser());
                                            ClipboardUtil.copy(prvm.getRvList().get(i).getUser());
                                        } else if ("复制账户".equals(text)) {
                                            ToastUtil.show("账户已复制:" + prvm.getRvList().get(i).getAccount());
                                            ClipboardUtil.copy(prvm.getRvList().get(i).getAccount());
                                        } else if ("复制密码".equals(text)) {
                                            String item = prvm.getRvList().get(i).getPsd();
                                            item = DecryptUtil.decrypt2(item);
                                            ToastUtil.show("密码已复制:" + item + "\n长按可快速复制");
                                            ClipboardUtil.copy(item);
                                        } else if ("删除".equals(text)) {
                                            AsyncUtils.run(emitter -> {
                                                AccountPO item = prvm.getRvList().get(i);
                                                item.setUpdateTime(System.currentTimeMillis());
                                                item.setDeleteflag((byte) 1);
                                                MainDatabase_Impl.getInstance().accountDao().updateItem(item);
                                                emitter.onNext("");
                                            }, data -> {
                                                queryList();
                                            });
                                        }
                                    })
                            .show();
                })
                .setRefreshLayout(binding.refreshLayout)
                .setEnableRefresh(false)
                .setEnableLoadMore(false)
                .init();
    }

    @Override
    protected void initData() {
        queryList();
    }

    @Override
    protected void initListener() {
        binding.imgEdit.setOnClickListener(v -> {
            Navigation.findNavController(binding.container).navigate(R.id.action_accountListFragment_to_accountEditFragment);
        });
//        binding.imgBackup.setOnClickListener(v -> {
//            Navigation.findNavController(binding.container).navigate(R.id.action_accountListFragment_to_backupFragment);
//        });
        binding.etSearch.setOnKeyListener((v, keyCode, event) -> {
            if (KeyEventUtil.isEnter(keyCode)) {
                queryList();
                return true;
            }
            return false;
        });
    }

    private void queryList() {
        AsyncUtils.run(emitter -> {
            String sql = " SELECT * FROM account WHERE deleteflag!=1 ";
            if (EmptyUtil.isNotEmpty(binding.etSearch.getText())) {
                sql += " AND ( account like '%" + binding.etSearch.getText() + "%' OR " +
                        " user like '%" + binding.etSearch.getText() + "%' OR " +
                        " note like '%" + binding.etSearch.getText() + "%' ) ";
            }
            sql += "ORDER BY account ";
            List<AccountPO> list = MainDatabase_Impl.getInstance().accountDao().getList(new SimpleSQLiteQuery(sql));
            emitter.onNext(list);
        }, (Consumer<List<AccountPO>>) data -> {
            prvm.freshData(data);
        });
    }

    public void jump2Edit(AccountPO item) {
        Bundle finalArgs = new Bundle();
        finalArgs.putString("data", item.getUuid());
        Navigation.findNavController(binding.container).navigate(R.id.action_accountListFragment_to_accountEditFragment, finalArgs);
    }

}